<?php

class GoodsImageController extends CommonController {
	
	public function __construct() {
		parent::__construct();
	}

	public function recordsAction() {
		$conditions = '';

		$page = (int) $this->requestGet('page', 1);
		$pageSize = (int) $this->requestGet('pageSize', 100);
		$offset = ($page - 1) * $pageSize;

		$orderField = (int) $this->requestGet('orderField', 0);
		$orderDirection = (int) $this->requestGet('orderDirection', 1);
		$fields = array('name', 'width', 'height', 'size');
		$field = isset($fields[$orderField]) ? $fields[$orderField] : $field[0];
		$direction = $orderDirection > 0 ? 'ASC' : 'DESC';
		$order = " ORDER BY `{$field}` {$direction} ";

		$totalQuery = "SELECT COUNT(`id`) as `total` FROM `goodsImage`";
		$db = $this->loadSqlite('bamboo');
		$totalRow = $db->getOne($totalQuery);
		$data = array('total' => $totalRow['total']);
		
		$query = "SELECT * FROM `goodsImage` WHERE 1 {$conditions} {$order} LIMIT {$offset}, {$pageSize}";
		$data['records'] = $db->getAll($query);

		$this->jsonSuccess('', $data);
	}

	public function genAction(){
		$db = $this->loadSqlite('bamboo');

		$db->truncate('goodsImage');
		$path = '/mnt/hgfs/wwwroot/cloudfront/images/phone_goods/';
		$images = scandir($path);
		foreach ($images as $key => $image) {
			if (in_array($image, array('.', '..', '.svn'))) {
				unset($images[$key]);
				continue;
			}

			$segments = explode('.', $image);
			switch($segments[1]){
				case 'png':
					$img = imagecreatefrompng($path . $image);
				break;
				case 'gif':
					$img = imagecreatefromgif($path . $image);
				break;
				default:
					continue;
			}
			

			$data = array(
				'name' => $image,
				'width' => imagesx($img),
				'height' => imagesy($img),
				'size' => filesize($path . $image)
			);

			imagedestroy($img);

			$db->set('goodsImage', $data);
		}

		$this->jsonSuccess('生成成功');
	}
}
?>